# Create your views here.
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from pydemo.polls.models import Choice, Poll

def index(request):
    last_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('index.html', {'last_poll_list':last_poll_list})
    
def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('detail.html',{'poll':p})

def results(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('results.html',{'poll':p})

def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        select_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render_to_response('detail.html', {'poll':p, 'error_message':'choice please'})
    else:
        select_choice.votes +=1
        select_choice.save()
        return
    HttpResponseRedirect(reverse('pydemo.polls.views.results',args=(p.id,)))

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    